using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PagesRangeInvertor
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		public static string Invert(string range)
		{
			Range r = new Range(range);
			r.Invert();
			return r.ToString();
		}

		private void textBox1_TextChanged(object sender, EventArgs e)
		{
			textBox2.Text = Invert(textBox1.Text);
		}
	}

	public class Range
	{
		#region ctor

		public Range(string range)
		{
			FillFrom(range);
		}

		#endregion

		private bool[] Numbers = new bool[1];

		#region Fill

		public void FillFrom(string range)
		{
			string[] parts = range.Split(',');
			foreach (string part in parts)
			{
				AddPart(part);
			}
		}

		public void AddPart(string part)
		{
			if (string.IsNullOrEmpty(part))
			{
				return;
			}
			int minus = part.IndexOf('-');
			if (minus < 0)
			{
				int num = -1;
				if (int.TryParse(part, out num))
				{
					AddNumber(num);
				}
			}
			else if (minus > 0 && minus < part.Length - 1)
			{
				string before = part.Substring(0, minus);
				string after = part.Substring(minus + 1);
				int b = int.Parse(before);
				int a = int.Parse(after);
				for (int i = b; i <= a; i++)
				{
					AddNumber(i);
				}
			}
		}

		public void AddNumber(int num)
		{
			if (num < 0)
			{
				return;
			}

			Grow(num);
			Numbers[num] = true;
		}

		public void Grow(int newSize)
		{
			if (newSize >= Numbers.Length - 1)
			{
				bool[] result = new bool[newSize + 1];
				Numbers.CopyTo(result, 0);
				Numbers = result;
			}
		}

		#endregion

		#region Output

		public override string ToString()
		{
			StringBuilder s = new StringBuilder();

			int startMark = -1;

			for (int i = 1; i < Numbers.Length; i++)
			{
				if (Numbers[i])
				{
					if (startMark == -1)
					{
						startMark = i;
					}
				}
				else
				{
					if (startMark != -1)
					{
						AddRange(s, startMark, i - 1);
					}
					startMark = -1;
				}
			}
			if (startMark != -1)
			{
				AddRange(s, startMark, Numbers.Length - 1);
			}

			return s.ToString();
		}

		public void AddRange(StringBuilder s, int start, int end)
		{
			if (end < start)
			{
				return;
			}
			else if (end == start)
			{
				AppendParam(s, start.ToString());
			}
			else
			{
				AppendParam(s, start.ToString() + "-" + end.ToString());
			}
		}

		public void AppendParam(StringBuilder s, string param)
		{
			if (s.Length > 0)
			{
				s.Append(",");
			}
			s.Append(param);
		}

		#endregion

		public void Invert()
		{
			for (int i = 0; i < Numbers.Length; i++)
			{
				Numbers[i] = !Numbers[i];
			}
		}
	}
}